/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import entity.ProductEntity;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
///
import entity.RedemptionListEntity;
import entity.RedemptionItemEntity;
import entity.ReservedFnBProductEntity;
import entity.ReservedMealEntity;
import entity.ReservedSetMealEntity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import util.entityhelper.ULPItemHelper;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import session.stateful.LoyaltyProgramSessionBean;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.SelectEvent;
import java.util.Date;
import util.entityhelper.AccumulationHelper;

/**
 *
 * @author NGUYEN CONG DAT
 */
@ManagedBean
@SessionScoped
public class TCubeULPManagerBean { 
    @EJB
    private LoyaltyProgramSessionBean loyaltyProgramSessionBean;
    //private StakeholderEntity stakeholder;
    private RedemptionListEntity ULPItem;

    private List<RedemptionListEntity> pendingULPItemApplicationList;
    private List<RedemptionListEntity> ULPItemApplicationList;
    private List<ULPItemHelper> expiredULPItemList;
    private List<ULPItemHelper> currentULPItemList;

    private RedemptionListEntity selectedULPItemApplication;
    private ULPItemHelper selectedULPItem;
    private boolean reloadPage = true;
    
    private Date inputDateFrom;
    private Date inputDateUntil;
    private List<RedemptionItemEntity> redemptionInPeriodList;
    private boolean displayRedemptions = false; 
    private RedemptionItemEntity selectedRedemption;
    private AccumulationHelper selectedAccumulation;
    private List<AccumulationHelper> accumulationList;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    
    /** Creates a new instance of ULPItemManagerBean */
    public TCubeULPManagerBean() {               
        loyaltyProgramSessionBean = new LoyaltyProgramSessionBean();
        //stakeholder = (StakeholderEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholder");                        
        ULPItem = new RedemptionListEntity();
        pendingULPItemApplicationList = new ArrayList<RedemptionListEntity>();
        ULPItemApplicationList = new ArrayList<RedemptionListEntity>();
        expiredULPItemList = new ArrayList<ULPItemHelper>();
        currentULPItemList = new ArrayList<ULPItemHelper>();
       
        selectedULPItemApplication = new RedemptionListEntity();
        selectedULPItem = new ULPItemHelper(null,null,null);
        redemptionInPeriodList = new ArrayList<RedemptionItemEntity>();
        selectedRedemption = new RedemptionItemEntity();
    }
    
     public ProductEntity getProductFromReservedFnBProduct(ReservedFnBProductEntity r) {
        ReservedMealEntity meal;
        ReservedSetMealEntity set;
        if (r instanceof ReservedMealEntity) {
            meal = (ReservedMealEntity) r;
            return meal.getMeal();
        } else {
            if (r instanceof ReservedSetMealEntity) {
                set = (ReservedSetMealEntity) r;
                return set.getSetMeal();
            } else {
                return null;
            }
        }
    }
     
    public void createULPItem(ActionEvent event) {
        try {                        
            getLoyaltyProgramSessionBean().tCubeCreateULPItem(getULPItem());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "ULP Item Application has been successfully created", ""));
            setReloadPage(true);
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "An error occurred ! ULPItem application cannot be created", ""));
            e.printStackTrace();
        }
    }
    
    public void doEditULPItem(ActionEvent event){
        try {                        
            getLoyaltyProgramSessionBean().editULPItem(getULPItem());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "ULP Item Application has been successfully editted", ""));
            setReloadPage(true);
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "An error occurred ! ULPItem application cannot be editted", ""));
            e.printStackTrace();
        }
    }
   
    // Initialize list of ULPItem APPLICATIONS For TCube
    public void initULPItemApplicationList(PhaseEvent event) throws IOException {
        setPendingULPItemApplicationList(getLoyaltyProgramSessionBean().getPendingULPItemApplicationList());
        setULPItemApplicationList(getLoyaltyProgramSessionBean().getAllULPItemApplicationList());
    }
    
    // Initialize list of ULPItems For TCube
    public void initULPItemList(PhaseEvent event) throws IOException {
        setCurrentULPItemList(getLoyaltyProgramSessionBean().getAllCurrentULPItems());
        setExpiredULPItemList(getLoyaltyProgramSessionBean().getExpiredULPItems());
    }
       
    public void initViewULPItem(PhaseEvent event) throws IOException {
        if (!checkULPItem()) {
            return;
        }
    }   
    
    public void initViewULPItemApplication(PhaseEvent event) throws IOException {
        if (!checkULPItemApplication()) {
            return;
        }
    }  
    
    public void initAddULPItem(PhaseEvent event) throws IOException {
        if (isReloadPage()) {
            setULPItem(new RedemptionListEntity());
            setReloadPage(false);
        }
    }
    
    
    // 
    public void retrieveRedemptionInPeriodList(ActionEvent event) throws IOException {
        redemptionInPeriodList = loyaltyProgramSessionBean.getAllRedemptionsByDate(inputDateFrom, inputDateUntil);
        displayRedemptions = true;
          String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewRedemptions.xhtml");
    }
    
    // 
    public void retrieveAllRedemptionList(ActionEvent event) throws IOException {
        redemptionInPeriodList = loyaltyProgramSessionBean.getAllRedemptions();
        displayRedemptions = true;
           String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewRedemptions.xhtml");
    }
    
    public boolean checkULPItem() throws IOException {
//        if (!checkStakeholder()) {
//            return false;
//        }
        setSelectedULPItem((ULPItemHelper) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedULPItem"));
        if (getSelectedULPItem().getULPItem()== null || getSelectedULPItem().getULPItem().getId() == null) {
              String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewAllULPItems.xhtml");
            return false;
        }
        return true;
    }
    
    public boolean checkULPItemApplication() throws IOException {
        setSelectedULPItemApplication((RedemptionListEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedULPItemApplication"));
        if (getSelectedULPItemApplication() == null || getSelectedULPItemApplication().getId() == null) {
                         String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewAllULPItemApplications.xhtml");
            return false;
        }
        return true;
    }
    
    public void initViewAccumulation(PhaseEvent event) throws IOException {
        setSelectedAccumulation((AccumulationHelper) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedAccumulation"));
        if (getSelectedAccumulation() == null || getSelectedAccumulation().getReservation() == null || getSelectedAccumulation().getReservation().getId() == null) {
                  String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewAccumulations.xhtml");
        }
    }
    
    public void initViewRedemption(PhaseEvent event) throws IOException {
        selectedRedemption = (RedemptionItemEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedRedemption");
        if (selectedRedemption == null || selectedRedemption.getId() == null) {
            String serverName = ctx.getExternalContext().getRequestServerName();
            int serverPort = (Integer) ctx.getExternalContext().getSessionMap().get("serverPort");
            String contextPath = ctx.getExternalContext().getRequestContextPath();
            ctx.getExternalContext().redirect("http://" + serverName + ":" + serverPort + contextPath + "/staff/TCubeViewRedemptions.xhtml");
        }
    }
    
    public String onRowSelectNavigateViewAccumulation(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedAccumulation", getSelectedAccumulation());
        return "staff/TCubeViewAccumulation?faces-redirect=true";
    }
    
    public String onRowSelectNavigateViewRedemption(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedRedemption", selectedRedemption);
        return "staff/TCubeViewRedemption?faces-redirect=true";
    }
    
    public String onRowNavigateULPItemApplication(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedULPItemApplication", getSelectedULPItemApplication());
        return "staff/TCubeViewULPItemApplication?faces-redirect=true";
    }

    public String onRowSelectNavigateULPItem(SelectEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedULPItem", getSelectedULPItem());
        return "staff/TCubeViewULPItem?faces-redirect=true";
    }
    
    public void acceptULPItemApplication(ActionEvent event) throws IOException {      
        getLoyaltyProgramSessionBean().acceptULPItemApplication(getSelectedULPItemApplication());
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "ULP Item has been successfully accepted",  "You can go back to the ULPItem application listing to see the changes");   
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public void denyULPItemApplication(ActionEvent event) throws IOException {;
        getLoyaltyProgramSessionBean().denyULPItemApplication(getSelectedULPItemApplication());
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "ULP Item has been successfully denied",  "You can go back to the ULPItem application listing to see the changes");   
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public String returnRedemptionStatus(boolean status) {
        if (status == true) {
            return "Voucher Redeemed";
        } else {
            return "Voucher Used";
        }
    }
    
    public void handleULPItemImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException {
        try {
            // Image uploaded by TCube
            System.out.println("Try to upload image");
            System.out.println(event.getFile().getFileName());
            String filePath = "C:\\is3102Project\\IS3102Project-war\\web\\images\\upload\\media\\TCube\\ULPItems\\";
            //String filePath = "C:\\IS3102Project\\IS3102Project-war\\web\\images";
            File file = new File(filePath);
            if (!file.exists()) {
                if ((new File(filePath)).mkdirs()) {
                }
            }
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName().replace(" ", "_"));
            System.out.println("result: " + result + " created");
            FileOutputStream out = new FileOutputStream(result);
            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];
            InputStream is = event.getFile().getInputstream();
            while (true) {
                a = is.read(buffer);
                if (a < 0) {
                    break;
                }
                out.write(buffer, 0, a);
                out.flush();
            }
            getULPItem().setImageURL("/TCube/ULPItems/" + event.getFile().getFileName().replace(" ", "_"));                        
            out.close();
            is.close();
            FacesMessage msg = new FacesMessage("Succesful " + event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
           
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public LoyaltyProgramSessionBean getLoyaltyProgramSessionBean() {
        return loyaltyProgramSessionBean;
    }

    public void setLoyaltyProgramSessionBean(LoyaltyProgramSessionBean loyaltyProgramSessionBean) {
        this.loyaltyProgramSessionBean = loyaltyProgramSessionBean;
    }

    public RedemptionListEntity getULPItem() {
        return ULPItem;
    }

    public void setULPItem(RedemptionListEntity ULPItem) {
        this.ULPItem = ULPItem;
    }

    public List<RedemptionListEntity> getPendingULPItemApplicationList() {
        return pendingULPItemApplicationList;
    }

    public void setPendingULPItemApplicationList(List<RedemptionListEntity> pendingULPItemApplicationList) {
        this.pendingULPItemApplicationList = pendingULPItemApplicationList;
    }

    public List<RedemptionListEntity> getULPItemApplicationList() {
        return ULPItemApplicationList;
    }

    public void setULPItemApplicationList(List<RedemptionListEntity> ULPItemApplicationList) {
        this.ULPItemApplicationList = ULPItemApplicationList;
    }

    public List<ULPItemHelper> getExpiredULPItemList() {
        return expiredULPItemList;
    }

    public void setExpiredULPItemList(List<ULPItemHelper> expiredULPItemList) {
        this.expiredULPItemList = expiredULPItemList;
    }

    public List<ULPItemHelper> getCurrentULPItemList() {
        return currentULPItemList;
    }

    public void setCurrentULPItemList(List<ULPItemHelper> currentULPItemList) {
        this.currentULPItemList = currentULPItemList;
    }

    public RedemptionListEntity getSelectedULPItemApplication() {
        return selectedULPItemApplication;
    }

    public void setSelectedULPItemApplication(RedemptionListEntity selectedULPItemApplication) {
        this.selectedULPItemApplication = selectedULPItemApplication;
    }

    public ULPItemHelper getSelectedULPItem() {
        return selectedULPItem;
    }

    public void setSelectedULPItem(ULPItemHelper selectedULPItem) {
        this.selectedULPItem = selectedULPItem;
    }

    public boolean isReloadPage() {
        return reloadPage;
    }

    public void setReloadPage(boolean reloadPage) {
        this.reloadPage = reloadPage;
    }

    public Date getInputDateFrom() {
        return inputDateFrom;
    }

    public void setInputDateFrom(Date inputDateFrom) {
        this.inputDateFrom = inputDateFrom;
    }

    public Date getInputDateUntil() {
        return inputDateUntil;
    }

    public void setInputDateUntil(Date inputDateUntil) {
        this.inputDateUntil = inputDateUntil;
    }

    public boolean isDisplayRedemptions() {
        return displayRedemptions;
    }

    public void setDisplayRedemptions(boolean displayRedemptions) {
        this.displayRedemptions = displayRedemptions;
    }

    public List<RedemptionItemEntity> getRedemptionInPeriodList() {
        return redemptionInPeriodList;
    }

    public void setRedemptionInPeriodList(List<RedemptionItemEntity> redemptionInPeriodList) {
        this.redemptionInPeriodList = redemptionInPeriodList;
    }

    public RedemptionItemEntity getSelectedRedemption() {
        return selectedRedemption;
    }

    public void setSelectedRedemption(RedemptionItemEntity selectedRedemption) {
        this.selectedRedemption = selectedRedemption;
    }

    public AccumulationHelper getSelectedAccumulation() {
        return selectedAccumulation;
    }

    public void setSelectedAccumulation(AccumulationHelper selectedAccumulation) {
        this.selectedAccumulation = selectedAccumulation;
    }

    public List<AccumulationHelper> getAccumulationList() {
        return accumulationList;
    }

    public void setAccumulationList(List<AccumulationHelper> accumulationList) {
        this.accumulationList = accumulationList;
    }
}
